<template>
  <div class="trade-add-page">
    <!-- 导航栏 -->
    <NavBar title="发布商品" />
    
    <!-- 表单内容 -->
    <div class="page-content">
      <van-form @submit="handleSubmit">
        <!-- 商品名称 -->
        <van-field
          v-model="form.title"
          name="title"
          label="商品名称"
          placeholder="请输入商品名称"
          :rules="[{ required: true, message: '请输入商品名称' }]"
        />
        
        <!-- 商品价格 -->
        <van-field
          v-model="form.price"
          name="price"
          label="商品价格"
          type="number"
          placeholder="请输入商品价格"
          :rules="[{ required: true, message: '请输入商品价格' }]"
        >
          <template #left-icon>
            <span style="color: #ff4444;">¥</span>
          </template>
        </van-field>
        
        <!-- 商品描述 -->
        <van-field
          v-model="form.description"
          name="description"
          label="商品描述"
          type="textarea"
          placeholder="请详细描述商品信息、使用情况、交易方式等"
          rows="4"
          :rules="[{ required: true, message: '请输入商品描述' }]"
        />
        
        <!-- 图片上传 -->
        <van-field name="images" label="商品图片">
          <template #input>
            <van-uploader
              v-model="form.images"
              multiple
              :max-count="3"
              :after-read="afterRead"
              :before-delete="beforeDelete"
            />
          </template>
        </van-field>
        
        <!-- 提交按钮 -->
        <div class="submit-section">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
          >
            发布商品
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavBar from '@/components/Common/NavBar.vue'
import { tradeApi } from '@/api/trade'
import { uploadApi } from '@/api/upload'

const router = useRouter()

// 表单数据
const form = ref({
  title: '',
  description: '',
  price: '',
  images: [] as any[]
})

const loading = ref(false)

// 图片上传后处理
const afterRead = async (file: any) => {
  try {
    // 检查文件大小（2M限制）
    if (file.file.size > 2 * 1024 * 1024) {
      showToast('图片大小不能超过2M')
      return
    }
    
    // 显示上传中状态
    file.status = 'uploading'
    file.message = '上传中...'
    
    const response = await uploadApi.uploadFile(file.file)
    if (response.code === 1) {
      file.url = response.data  // 直接使用data字段，它就是URL字符串
      file.status = 'done'
      file.message = ''
    } else {
      file.status = 'failed'
      file.message = '上传失败'
      showToast('图片上传失败')
    }
  } catch (error) {
    file.status = 'failed'
    file.message = '上传失败'
    showToast('图片上传失败')
    console.error('图片上传失败:', error)
  }
}

// 删除图片前确认
const beforeDelete = () => {
  return true
}

// 提交表单
const handleSubmit = async () => {
  loading.value = true
  
  try {
    // 处理图片URL - 只传入有效的URL
    const imageUrls = form.value.images
      .filter(img => img.url && img.status === 'done')
      .map(img => img.url)
    
    // 准备提交数据，根据TradeDto结构
    const submitData: any = {
      title: form.value.title,
      description: form.value.description,
      price: parseFloat(form.value.price)
    }
    
    // 只有当有图片URL时才设置对应字段，没有的不传入（保持undefined）
    if (imageUrls.length > 0) submitData.pic1 = imageUrls[0]
    if (imageUrls.length > 1) submitData.pic2 = imageUrls[1]
    if (imageUrls.length > 2) submitData.pic3 = imageUrls[2]
    
    const result = await tradeApi.add(submitData)
    if (result.code === 1) {
      showToast('发布成功')
      router.back()
    } else {
      showToast(result.msg || '发布失败')
    }
  } catch (error) {
    showToast('发布失败')
    console.error('发布失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.trade-add-page {
  min-height: 100vh;
  background-color: #f1f1f1;
}

.page-content {
  padding: 16px;
}

.submit-section {
  margin-top: 24px;
  padding: 0 16px;
}
</style>